home *** CD-ROM | disk | FTP | other *** search
- Infix Calc
- Previous: <RPN Calc=>RPNCalc> * Next: <Simple Error Recovery=>SimpleErro> * Up: <Examples=>Examples>
-
- #Wrap on
- {fH3}Infix Notation Calculator: {fCode}calc{f}{f}
-
- We now modify rpcalc to handle infix operators instead of postfix. Infix
- notation involves the concept of operator precedence and the need for
- parentheses nested to arbitrary depth. Here is the Bison code for
- {fCite}calc.y{f}, an infix desk-top calculator.
-
- #Wrap off
- #fCode
- \/\* Infix notation calculator--calc \*\/
-
- %\{
- \#define YYSTYPE double
- \#include <math.h>
- %\}
-
- \/\* BISON Declarations \*\/
- %token NUM
- %left '-' '+'
- %left '\*' '\/'
- %left NEG \/\* negation--unary minus \*\/
- %right '^' \/\* exponentiation \*\/
-
- \/\* Grammar follows \*\/
- %%
- input: \/\* empty string \*\/
- | input line
- ;
-
- line: '\\n'
- | exp '\\n' \{ printf ("\\t%.10g\\n", $1); \}
- ;
-
- exp: NUM \{ $$ = $1; \}
- | exp '+' exp \{ $$ = $1 + $3; \}
- | exp '-' exp \{ $$ = $1 - $3; \}
- | exp '\*' exp \{ $$ = $1 \* $3; \}
- | exp '\/' exp \{ $$ = $1 \/ $3; \}
- | '-' exp %prec NEG \{ $$ = -$2; \}
- | exp '^' exp \{ $$ = pow ($1, $3); \}
- | '(' exp ')' \{ $$ = $2; \}
- ;
- %%
- #f
- #Wrap on
-
- The functions {fCode}yylex{f}, {fCode}yyerror{f} and {fCode}main{f} can be the same
- as before.
-
- There are two important new features shown in this code.
-
- In the second section (Bison declarations), {fCode}%left{f} declares token
- types and says they are left-associative operators. The declarations
- {fCode}%left{f} and {fCode}%right{f} (right associativity) take the place of
- {fCode}%token{f} which is used to declare a token type name without
- associativity. (These tokens are single-character literals, which
- ordinarily don't need to be declared. We declare them here to specify
- the associativity.)
-
- Operator precedence is determined by the line ordering of the
- declarations; the higher the line number of the declaration (lower on
- the page or screen), the higher the precedence. Hence, exponentiation
- has the highest precedence, unary minus ({fCode}NEG{f}) is next, followed
- by {fEmphasis}\*{f} and {fEmphasis}\/{f}, and so on. \*Note <Precedence=>Precedencf>: Operator Precedence.
-
- The other important new feature is the {fCode}%prec{f} in the grammar section
- for the unary minus operator. The {fCode}%prec{f} simply instructs Bison that
- the rule {fEmphasis}| '-' exp{f} has the same precedence as {fCode}NEG{f}---in this
- case the next-to-highest. \*Note <Contextual Precedence=>Contextual>: Context-Dependent Precedence.
-
- Here is a sample run of {fCite}calc.y{f}:
-
- #Wrap off
- #fCode
- % calc
- 4 + 4.5 - (34\/(8\*3+-3))
- 6.880952381
- -56 + 2
- -54
- 3 ^ 2
- 9
- #f
- #Wrap on
-
-